package com.jueming.miser.auth.interceptor;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jueming.miser.auth.to.MiserUserTo;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Description: 自定义拦截器,在执行目标方法之前，判断用户的登录状态.并封装传递给controller目标请求
 **/

public class CartInterceptor implements HandlerInterceptor {


    public static ThreadLocal<MiserUserTo> toThreadLocal = new ThreadLocal<>();

    /***
     * 目标方法执行之前提取登录信息
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        MiserUserTo to;

        HttpSession session = request.getSession();
        //获得当前登录用户的信息
//        ObjectMapper objectMapper = new ObjectMapper();
//        to = objectMapper.readValue(session.getAttribute("loginUser").toString(), new TypeReference<MiserUserTo>() {});

//        String s = JSON.toJSONString(session.getAttribute("loginUser"));
        if (session == null) {
            return true;
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            return true;
        }
        to = JSON.parseObject(loginUser.toString(), MiserUserTo.class);

        if (to != null) {
            //用户登录了
            toThreadLocal.set(to);
            return true;
        } else{
            return true;
        }
    }

}
